package com.huaboot.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huaboot.commont.page.PageResult;
import com.huaboot.system.convert.SysDictDataConvert;
import com.huaboot.system.entity.SysDictDataEntity;
import com.huaboot.system.entity.SysDictTypeEntity;
import com.huaboot.system.mapper.SysDictDataMapper;
import com.huaboot.system.query.SysDictDataQuery;
import com.huaboot.system.service.SysDictDataService;
import com.huaboot.system.service.SysDictTypeService;
import com.huaboot.system.vo.SysDictDataVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 数据字典

 */
@Service
@AllArgsConstructor
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictDataEntity> implements SysDictDataService {

    private final SysDictTypeService sysDictTypeService;
    @Override
    public PageResult<SysDictDataVO> page(SysDictDataQuery query) {
        PageHelper.startPage(query.currentPage, query.size);
        List<SysDictDataEntity> sysDictDataEntityList = list(getWrapper(query));
        PageInfo<SysDictDataEntity> page = new PageInfo<>(sysDictDataEntityList);
        return new PageResult<>(SysDictDataConvert.INSTANCE.convertList(page.getList()), page.getTotal());
    }

    private Wrapper<SysDictDataEntity> getWrapper(SysDictDataQuery query){
        LambdaQueryWrapper<SysDictDataEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDictDataEntity::getDictTypeId, query.getDictTypeId());
        wrapper.orderByAsc(SysDictDataEntity::getSort);
        return wrapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysDictDataVO vo) {
        SysDictDataEntity entity = SysDictDataConvert.INSTANCE.convert(vo);
        baseMapper.insert(entity);
        sysDictTypeService.refreshTransCache();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysDictDataVO vo) {
        SysDictDataEntity entity = SysDictDataConvert.INSTANCE.convert(vo);
        updateById(entity);
        sysDictTypeService.refreshTransCache();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
        sysDictTypeService.refreshTransCache();
    }

}
